package com.hadwinling.service.impl;

import cn.hutool.core.io.file.FileReader;
import com.hadwinling.entity.Burn;
import com.hadwinling.entity.NuclearParam;
import com.hadwinling.entity.ShikeTime;
import com.hadwinling.mapper.BurnMapper;
import com.hadwinling.mapper.ShikeTimeMapper;
import com.hadwinling.service.IoTDBService;
import org.apache.iotdb.rpc.IoTDBConnectionException;
import org.apache.iotdb.rpc.StatementExecutionException;
import org.apache.iotdb.session.Session;
import org.apache.iotdb.session.SessionDataSet;
import org.apache.iotdb.tsfile.file.metadata.enums.TSDataType;
import org.apache.iotdb.tsfile.read.common.Field;
import org.apache.iotdb.tsfile.read.common.RowRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @Classname IoTDBServiceImpl
 * @Description TODO
 * @Date 2021/7/3 15:29
 * @Created by
 */
@Service
public class IoTDBServiceImpl implements IoTDBService {
    @Autowired
    private Session iotdbSession;
    @Autowired
    private BurnMapper burnMapper;
    @Autowired
    private ShikeTimeMapper shikeTimeMapper;

    @Override
    public void setStorageGroup(String storageGroup) {
        try {
            iotdbSession.setStorageGroup(storageGroup);
        } catch (IoTDBConnectionException e) {
            e.printStackTrace();
        } catch (StatementExecutionException e) {
            e.printStackTrace();
        }
    }


    @Override
    public void deleteStorageGroup(String storageGroup) {
        try {
            iotdbSession.deleteStorageGroup(storageGroup);
        } catch (IoTDBConnectionException e) {
            e.printStackTrace();
        } catch (StatementExecutionException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void insert(String storage, int zujianNum, int zhibiaoNum) {
//        FileReader fileReader = new FileReader("D:\\MySoftWare\\PCWare\\Tencent\\AppCache\\WetChatCache\\WeChat Files\\wxid_ysw3yj1tpdwp22\\FileStorage\\File\\2021-06\\go30");
        FileReader fileReader = new FileReader("/home/hedian/go30");

        List<String> lines = fileReader.readLines();
        int line = 0;
        long timestamp = System.currentTimeMillis();

        String[] shujukuaiArray = {"gl", "kq", "rq", "s", "d", "wd"}; //gl:功率 kq：快群 rq：热群 s: 氙 d: 碘 wd：温度

        List<String> deviceIds = new ArrayList<>();
        List<List<String>> measurementsList = new ArrayList<>();
        List<List<Object>> valuesList = new ArrayList<>();
        List<Long> timestamps = new ArrayList<>();
        List<List<TSDataType>> typesList = new ArrayList<>();

        List<String> measurements = new ArrayList<>();
        List<TSDataType> types = new ArrayList<>();
        for (int i = 0; i < 32; i++) {
            measurements.add("s" + (i + 1));
            types.add(TSDataType.FLOAT);
        }

        ShikeTime shikeTime = new ShikeTime(); // 记录时刻

        for (int rhb = 0; rhb < 18; rhb++) {
            Burn burn = new Burn(); // 记录燃耗步
            burn.setBurnid(rhb + 1); // 记录燃耗步id
            burn.setStart(timestamp + "");//燃耗步开始时间

            shikeTime.setBurnid(rhb + 1);//记录时刻表中的燃耗步id

            for (int zb = 0; zb < zhibiaoNum; zb++) {// 6 个指标

                shikeTime.setIndicatorid(zb);

                for (int shike = 0; shike < 98; shike++) { // 98 个时刻
                    shikeTime.setStart(timestamp + "");

                    for (int zj = 0; zj < zujianNum; zj++) { // 52 个组件-

                        String deviceId = storage + "." + shujukuaiArray[zb] + ".zj" + zj;
                        List<Object> values = new ArrayList<>();
                        final String[] s = lines.get(line).split(" ");
                        for (int i = 0; i < 32; i++) {
                            String value = s[i];
                            values.add(Float.parseFloat(value));
                        }
                        line++;
                        deviceIds.add(deviceId);
                        valuesList.add(values);
                        measurementsList.add(measurements);
                        typesList.add(types);
                        timestamps.add(timestamp);
                    }
                    try {
                        iotdbSession.insertRecords(deviceIds, timestamps, measurementsList, typesList, valuesList);
                    } catch (IoTDBConnectionException e) {
                        e.printStackTrace();
                    } catch (StatementExecutionException e) {
                        e.printStackTrace();
                    }

                    deviceIds.clear();
                    measurementsList.clear();
                    valuesList.clear();
                    timestamps.clear();

                    shikeTime.setTimeid(shike);
                    timestamp = timestamp + 1000; // 1秒一个时刻
                    shikeTime.setEnd(timestamp + "");
                    shikeTimeMapper.insert(shikeTime);

                }
            }
            burn.setEnd(timestamp + "");
            burnMapper.insert(burn);
        }
    }


    /**
     * 2.1 plot_burn_ind_mod (burn,indicator,module)
     * 给定 燃耗步，指标，组件值；得层、时刻的变化（3D）
     *
     * @param nuclearParam 传过来的值
     * @return
     */
    @Override
    public SessionDataSet plot_burn_indicator_module(NuclearParam nuclearParam) {
        final List<Burn> burns = burnMapper.selectAllByBurnidBetweenBurnid(nuclearParam.getBurn_start(), nuclearParam.getBurn_end());
        String burn_Start_time = burns.get(0).getStart();
        String burn_end_time = burns.get(burns.size() - 1).getEnd();

        String[] shujukuaiArray = {"gl", "kq", "rq", "s", "d", "wd"}; //gl:功率 kq：快群 rq：热群 s: 氙 d: 碘 wd：温度

        StringBuffer stringBuffer = new StringBuffer();
        for (int i = 0; i < 32; i++) {
            stringBuffer.append("s" + i + ", ");
            if (i == 31) {
                stringBuffer.append("s" + (i + 1) + " ");
            }
        }
        SessionDataSet sessionDataSet = null;
        try {
//            System.out.println("select " + stringBuffer.toString() + "from root.dc_dx1." + shujukuaiArray[nuclearParam.getIndicator()-1] + ".zj" + (nuclearParam.getModule()-1) + " where time > " + burn_Start_time + " and time < " + burn_end_time);
            sessionDataSet = iotdbSession.executeQueryStatement("select " + stringBuffer.toString() + "from root.dc_dx1." + shujukuaiArray[nuclearParam.getIndicator() - 1] + ".zj" + (nuclearParam.getModule() - 1) + " where time >= " + burn_Start_time + " and time < " + burn_end_time);
        } catch (StatementExecutionException e) {
            e.printStackTrace();
        } catch (IoTDBConnectionException e) {
            e.printStackTrace();
        }
        return sessionDataSet;
    }

    /**
     * 2.2 plot_act_burn_ind_mod(burn,indicator,module)
     * 给定 燃耗步，指标，组件值；得层、时刻的变化（2D动态图）
     *
     * @param nuclearParam 传过来的值
     * @return
     */
    @Override
    public SessionDataSet plot_act_burn_ind_mod(NuclearParam nuclearParam) {
        final List<Burn> burns = burnMapper.selectAllByBurnidBetweenBurnid(nuclearParam.getBurn_start(), nuclearParam.getBurn_end());
        String burn_Start_time = burns.get(0).getStart();
        String burn_end_time = burns.get(burns.size() - 1).getEnd();

        String[] shujukuaiArray = {"gl", "kq", "rq", "s", "d", "wd"}; //gl:功率 kq：快群 rq：热群 s: 氙 d: 碘 wd：温度

        StringBuffer stringBuffer = new StringBuffer();
        for (int i = 0; i < 32; i++) {
            stringBuffer.append("s" + i + ", ");
            if (i == 31) {
                stringBuffer.append("s" + (i + 1) + " ");
            }
        }
        SessionDataSet sessionDataSet = null;
        try {
            sessionDataSet = iotdbSession.executeQueryStatement("select " + stringBuffer.toString() + "from root.dc_dx1." + shujukuaiArray[nuclearParam.getIndicator() - 1] + ".zj" + (nuclearParam.getModule() - 1) + " where time >= " + burn_Start_time + " and time < " + burn_end_time);
        } catch (StatementExecutionException e) {
            e.printStackTrace();
        } catch (IoTDBConnectionException e) {
            e.printStackTrace();
        }
        return sessionDataSet;
    }

    /**
     * 2.3 plot_mod_ind_time(module,indicator,time)
     * #给定组件、指标、时刻, 得燃耗步、层 变化（3D图）
     *
     * @param nuclearParam 传过来的值
     * @return
     */
    @Override
    public ArrayList<List<Field>> plot_mod_ind_time(NuclearParam nuclearParam) throws StatementExecutionException, IoTDBConnectionException {
        String[] shujukuaiArray = {"gl", "kq", "rq", "s", "d", "wd"}; //gl:功率 kq：快群 rq：热群 s: 氙 d: 碘 wd：温度
        final List<ShikeTime> shikeTimes = shikeTimeMapper.selectAllByTimeidAndIndicatorid(nuclearParam.getTime_start() - 1, nuclearParam.getIndicator() - 1);

        StringBuffer stringBuffer = new StringBuffer();
        for (int i = 0; i < 32; i++) {
            stringBuffer.append("s" + i + ", ");
            if (i == 31) {
                stringBuffer.append("s" + (i + 1) + " ");
            }
        }
        ArrayList<List<Field>> arrayLists = new ArrayList<>();
        for (int i = 0; i < shikeTimes.size(); i++) {
            ShikeTime shikeTime = shikeTimes.get(i);
//            System.out.println("select " + stringBuffer.toString() + "from root.dc_dx1." + shujukuaiArray[nuclearParam.getIndicator() - 1] + ".zj" + (nuclearParam.getModule() - 1) + " where time>=" + shikeTime.getStart() + " and time < " + shikeTime.getEnd());
            SessionDataSet sessionDataSet = iotdbSession.executeQueryStatement("select " + stringBuffer.toString() + "from root.dc_dx1." + shujukuaiArray[nuclearParam.getIndicator() - 1] + ".zj" + (nuclearParam.getModule() - 1) + " where time>=" + shikeTime.getStart() + " and time < " + shikeTime.getEnd());
            while (sessionDataSet.hasNext()) {
                final List<Field> fields = sessionDataSet.next().getFields();
                arrayLists.add(fields);
            }
        }

        return arrayLists;
    }

    /**
     * 2.4 plot_mod_lay_ind(module,layer,indicator)
     * #给定组件、层，指标，展示燃耗步、时刻、值的变化（3D图）
     *
     * @param nuclearParam 传过来的值
     * @return
     */
    @Override
    public SessionDataSet plot_mod_lay_ind(NuclearParam nuclearParam) {
        String[] shujukuaiArray = {"gl", "kq", "rq", "s", "d", "wd"}; //gl:功率 kq：快群 rq：热群 s: 氙 d: 碘 wd：温度
        SessionDataSet sessionDataSet = null;
        try {
            sessionDataSet = iotdbSession.executeQueryStatement("select s" + nuclearParam.getLayer() + " from root.dc_dx1." + shujukuaiArray[nuclearParam.getIndicator() - 1] + ".zj" + (nuclearParam.getModule() - 1));
        } catch (StatementExecutionException e) {
            e.printStackTrace();
        } catch (IoTDBConnectionException e) {
            e.printStackTrace();
        }
        return sessionDataSet;
    }


    /**
     * 2.5plot_mod_lay_ind_2d(module,layer,indicator)
     * #给定组件、层，指标，展示燃耗步、时刻、值的变化（2D图）
     *
     * @param nuclearParam
     * @return
     */
    @Override
    public SessionDataSet plot_mod_lay_ind_2d(NuclearParam nuclearParam) {
        String[] shujukuaiArray = {"gl", "kq", "rq", "s", "d", "wd"}; //gl:功率 kq：快群 rq：热群 s: 氙 d: 碘 wd：温度
        SessionDataSet sessionDataSet = null;
        try {
            sessionDataSet = iotdbSession.executeQueryStatement("select s" + nuclearParam.getLayer() + " from root.dc_dx1." + shujukuaiArray[nuclearParam.getIndicator() - 1] + ".zj" + (nuclearParam.getModule() - 1));
        } catch (StatementExecutionException e) {
            e.printStackTrace();
        } catch (IoTDBConnectionException e) {
            e.printStackTrace();
        }
        return sessionDataSet;
    }

    /**
     * 2.6plot_butn_ind_time(burn,indicator,time)
     * #给定燃耗步，指标，时刻，展示组件、层、值的变化（3D图）
     *
     * @param nuclearParam
     * @return
     */
    @Override
    public ArrayList<List<Field>> plot_butn_ind_time(NuclearParam nuclearParam) throws StatementExecutionException, IoTDBConnectionException, InterruptedException {
        String[] shujukuaiArray = {"gl", "kq", "rq", "s", "d", "wd"}; //gl:功率 kq：快群 rq：热群 s: 氙 d: 碘 wd：温度

        final List<ShikeTime> shikeTimes = shikeTimeMapper.selectAllByBurnidAndIndicatorid(nuclearParam.getBurn_start(), nuclearParam.getIndicator() - 1);

        StringBuffer stringBuffer = new StringBuffer();
        for (int i = 0; i < 32; i++) {
            stringBuffer.append("s" + i + ", ");
            if (i == 31) {
                stringBuffer.append("s" + (i + 1) + " ");
            }
        }
        final ArrayList<List<Field>> lists = new ArrayList<>();
        for (int i = 0; i < 52; i++) {
//            System.out.println("select " + stringBuffer.toString() + " from root.dc_dx1." + shujukuaiArray[nuclearParam.getIndicator() - 1] + ".zj" + i + " where time >= " + shikeTimes.get(nuclearParam.getTime_start()).getStart() + " and time <= " + shikeTimes.get(nuclearParam.getTime_start()).getEnd());
            final SessionDataSet sessionDataSet = iotdbSession.executeQueryStatement("select " + stringBuffer.toString() + " from root.dc_dx1." + shujukuaiArray[nuclearParam.getIndicator() - 1] + ".zj" + i + " where time >= " + shikeTimes.get(nuclearParam.getTime_start() - 1).getStart() + " and time < " + shikeTimes.get(nuclearParam.getTime_start() - 1).getEnd());
            while (sessionDataSet.hasNext()) {
                final List<Field> fields = sessionDataSet.next().getFields();
//                System.out.println(fields);
                lists.add(fields);
            }
        }
        return lists;
    }

    /**
     * 2.7 plot_burn_ind(burn,indicator,m_s=0,m_e=5,t_s=0,t_e=10):
     * #给定燃耗步，指标，展示时刻、组件、层、值的变化（3D四维图）
     *
     * @param nuclearParam
     * @return
     */
    @Override
    public ArrayList<List<Field>> plot_burn_ind(NuclearParam nuclearParam) throws StatementExecutionException, IoTDBConnectionException, InterruptedException {
        String[] shujukuaiArray = {"gl", "kq", "rq", "s", "d", "wd"}; //gl:功率 kq：快群 rq：热群 s: 氙 d: 碘 wd：温度

        final List<ShikeTime> shikeTimes = shikeTimeMapper.selectAllByBurnidAndIndicatorid(nuclearParam.getBurn_start(), nuclearParam.getIndicator() - 1);

        StringBuffer stringBuffer = new StringBuffer();
        for (int i = 0; i < 32; i++) {
            stringBuffer.append("s" + i + ", ");
            if (i == 31) {
                stringBuffer.append("s" + (i + 1) + " ");
            }
        }

        final ArrayList<List<Field>> lists = new ArrayList<>();
        for (int i = nuclearParam.getModule(); i <= nuclearParam.getModule_end(); i++) {
            for (int j = nuclearParam.getTime_start(); j <= nuclearParam.getTime_end(); j++) {
                final SessionDataSet sessionDataSet = iotdbSession.executeQueryStatement("select " + stringBuffer.toString() + " from root.dc_dx1." + shujukuaiArray[nuclearParam.getIndicator() - 1] + ".zj" + (i - 1) + " where time >= " + shikeTimes.get(j - 1).getStart() + " and time < " + shikeTimes.get(j - 1).getEnd());
                while (sessionDataSet.hasNext()) {
                    final List<Field> fields = sessionDataSet.next().getFields();
                    lists.add(fields);
                }
            }
        }
        return lists;
    }


    @Override
    public ArrayList<List<Field>> plot_burn_time_indicator(NuclearParam nuclearParam) throws StatementExecutionException, IoTDBConnectionException {
        String[] shujukuaiArray = {"gl", "kq", "rq", "s", "d", "wd"}; //gl:功率 kq：快群 rq：热群 s: 氙 d: 碘 wd：温度
        final List<ShikeTime> shikeTimes = shikeTimeMapper.selectAllByBurnidAndTimeidAndIndicatorid(nuclearParam.getBurn_start(), nuclearParam.getTime_start() - 1, nuclearParam.getIndicator() - 1);

        StringBuffer stringBuffer = new StringBuffer();
        for (int i = 0; i < 32; i++) {
            stringBuffer.append("s" + i + ", ");
            if (i == 31) {
                stringBuffer.append("s" + (i + 1) + " ");
            }
        }

        final ArrayList<List<Field>> lists = new ArrayList<>();
        for (int i = 0; i < 52; i++) {
            final SessionDataSet sessionDataSet = iotdbSession.executeQueryStatement("select " + stringBuffer.toString() + " from root.dc_dx1." + shujukuaiArray[nuclearParam.getIndicator() - 1] + ".zj" + i + " where time >= " + shikeTimes.get(0).getStart() + " and time < " + shikeTimes.get(0).getEnd());
            while (sessionDataSet.hasNext()) {
                final RowRecord next = sessionDataSet.next();
                final List<Field> fields = next.getFields();
                lists.add(fields);
            }
        }
        return lists;
    }


}
